package cn.edu.scau.dormitory_management_system.service.impl;

import cn.edu.scau.dormitory_management_system.dao.RolePermissionDao;
import cn.edu.scau.dormitory_management_system.entity.RolePermissionEntity;
import cn.edu.scau.dormitory_management_system.entity.UserEntity;
import cn.edu.scau.dormitory_management_system.service.RolePermissionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;

@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionDao, RolePermissionEntity> implements RolePermissionService {
    @Autowired(required = false)
    RolePermissionDao rolePermissionDao;
    @Override
    public int insert(int id, String permission, UserEntity user) {
        String[] split = permission.split(",");
        int count = 0;
        for (int i = 0; i < split.length; i++) {
            if(Integer.valueOf(split[i]) == -666666){
                count++;
                continue;
            }
            RolePermissionEntity rolePermissionEntity = new RolePermissionEntity();
            rolePermissionEntity.setRoleId(id);
            rolePermissionEntity.setPermissionId(Integer.valueOf(split[i]));
            rolePermissionEntity.setCreateBy(String.valueOf(user.getUserId()));
            rolePermissionDao.insert(rolePermissionEntity);
            count++;
        }
        return count == split.length?1:0;
    }
    @Override
    public int update(int id, String permission, UserEntity user) {
        String[] split = permission.split(",");
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("role_id",id);
        rolePermissionDao.deleteByMap(hashMap);
        int count = 0;
        for (int i = 0; i < split.length; i++) {
            if(Integer.valueOf(split[i]) == -666666){
                count++;
                continue;
            }
            RolePermissionEntity rolePermissionEntity = new RolePermissionEntity();
            rolePermissionEntity.setRoleId(id);
            rolePermissionEntity.setPermissionId(Integer.valueOf(split[i]));
            rolePermissionEntity.setCreateBy(String.valueOf(user.getUserId()));
            rolePermissionDao.insert(rolePermissionEntity);
            count++;
        }
        return count == split.length?1:0;
    }
}
